package com.llsly.library.service;

import com.llsly.library.model.Book;
import com.llsly.library.repository.BookRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class LibraryService {
    @Autowired
    private BookRepository bookRepository;

    // 添加书籍
    public Book addBook(Book book) {
        return bookRepository.save(book);
    }

    // 移除书籍
    public void removeBook(Long id) {
        if (!bookRepository.existsById(id)) {
            throw new IllegalArgumentException("书籍ID不存在: " + id);
        }
        bookRepository.deleteById(id);
    }

    // 获取书籍数量
    public long getBookCount() {
        return bookRepository.count();
    }

    // 检查是否有指定书名的书
    public boolean hasBook(String title) {
        return bookRepository.findByTitle(title) != null;
    }

    // 更新书籍信息
    public Book updateBook(Long id, Book updatedBook) {
        return bookRepository.findById(id)
                .map(existingBook -> {
                    if (updatedBook.getTitle() != null) {
                        existingBook.setTitle(updatedBook.getTitle());
                    }
                    if (updatedBook.getAuthor() != null) {
                        existingBook.setAuthor(updatedBook.getAuthor());
                    }
                    if (updatedBook.getIsbn() != null) {
                        existingBook.setIsbn(updatedBook.getIsbn());
                    }
                    return bookRepository.save(existingBook);
                })
                .orElseThrow(() -> new IllegalArgumentException("书籍ID不存在: " + id));
    }
}